package com.kaesar.leetcode.LeetCode_100_150;

import com.kaesar.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class LeetCode_102 {
    /**
     * 利用队列遍历二叉树：队列的特性是先进先出
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        // 暂存每一行的节点
        Queue<TreeNode> nodes = new LinkedList<>();
        nodes.add(root);
        while (!nodes.isEmpty()) {
            // 每次遍历一行数据
            List<Integer> vals = new ArrayList<>();
            int count = nodes.size();
            while (count > 0) {
                TreeNode curNode = nodes.poll();
                vals.add(curNode.val);
                // 将当前节点的左右子节点从左到右放入队列
                if (curNode.left != null) {
                    nodes.add(curNode.left);
                }
                if (curNode.right != null) {
                    nodes.add(curNode.right);
                }
                count--;
            }
            result.add(vals);
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        for (List<Integer> integers : levelOrder(root)) {
            for (Integer integer : integers) {
                System.out.print(integer + " ");
            }
            System.out.println();
        }
    }
}
